package sk.gunna.sms.server.user;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import sk.gunna.sms.client.user.UserService;
import sk.gunna.sms.shared.UserBean;

public class UserServiceImpl extends RemoteServiceServlet implements UserService{

	private static final long serialVersionUID = 1L;
	
	private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("transactions-optional");
	private static final Logger LOG = Logger.getLogger(UserServiceImpl.class.getName());
	
	@Override
	public void addUser(String userEmail, String userType) {
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.makePersistent(new AppUser(userEmail, userType));
			LOG.log(Level.INFO, "Add new user: "+ userEmail);
		} finally {
			pm.close();
		}
	}
	
	private PersistenceManager getPersistenceManager() {
		return PMF.getPersistenceManager();
	}

	@Override
	public List<UserBean> getUsers() {
		PersistenceManager pm = getPersistenceManager();
		List<UserBean> users = new ArrayList<UserBean>();
		try {
			Query q = pm.newQuery(AppUser.class);
			q.setOrdering("userEmail");
			List<AppUser> storedUsers = (List<AppUser>) q.execute();
			for ( AppUser appUser : storedUsers) {
				UserBean user = new UserBean();
				user.setUserEmail(appUser.getUserEmail());
				user.setCreateDate(appUser.getCreateDate());
				user.setUserType(appUser.getUserType());
				user.setLastLogin(appUser.getLastLogin());
				users.add(user);
			}
			
		} finally {
			pm.close();
		}
		return users;
	}

}
